<template>
  <div class="box">
    <div class="wrapper" :class="{ 'form-success': isHide }">
      <div class="container">
        <h1>登录cwk的小铺！</h1>

        <form class="form" :class="{ hide: isHide }">
          <input type="tel" name="tel" placeholder="telephone" v-model="form.phone" />
          <input type="password" placeholder="Password" v-model="form.password" />
          <button type="submit" id="login-button" @click.prevent="login">Login</button>
        </form>
      </div>

      <ul class="bg-bubbles">
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </div>
  </div>
</template>

<script>
import bus from '@/eventBus.js'
import { userLogin } from '@/api/index.js'
import { setExpire } from '@/utils/index.js'
export default {
  data() {
    return {
      isHide: false,
      form: {
        phone: '',
        password: ''
      }
    }
  },
  methods: {
    async login() {
      if (this.form.phone.trim() === '' || this.form.phone.length !== 11) {
        return this.open({ msg: '请输入正确格式电话号码', title: '填写错误' })
      }
      if (this.form.password.trim() === '' || this.form.password.length < 6 || this.form.password.length > 16) {
        return this.open({ msg: '请输入6到16位密码', title: '填写错误' })
      }
      const { data } = await userLogin('/api/home/userlogin', { params: this.form })
      if (data.message === 'success') {
        const expire = 60 * 10 * 1000
        setExpire('accessToken', data.customId, expire)
        localStorage.setItem('isDeliveryman', data.isDeliveryman)
        console.log(data)
        localStorage.setItem('username', data.username)
        this.$router.push('home')
      } else {
        this.open({ msg: data.message, title: '信息错误' })
      }
    },

    open(data) {
      this.$alert(data.msg, data.title, {
        confirmButtonText: '确定'
      })
    }
  },
  beforeDestroy() {
    bus.$emit('isLogin')
  }
}
</script>

<style lang="less" src="@/assets/css/userLogin.less" scoped></style>
<style lang="less" scoped></style>
